<?php
function wpInsertPost($my_post){
	try{
		// build post data
		$postDate = date('Y-m-d H:i:s', time());
		/*$my_post['post_title'] = $postTitle;
		$my_post['post_content'] = $postContent;
		$my_post['post_status'] = 'publish';
		$my_post['post_author'] = intval(rand(2,4));
		$my_post['tags_input'] = $hashtags;
		$my_post['post_category'] = array(1);
		$my_post['post_date'] = $postDate;
		$my_post['post_date_gmt'] = $postDate;
		// $my_post['image'] = Path of image
		*/
		$byPassImage = false;
		if(strstr($my_post['post_content'], '<iframe')){
			$byPassImage = true;
		}
		if(($my_post['image'] == null || $my_post['image'] == '') && !$byPassImage){
			return null;
		}
		$file = null;
		if(trim($my_post['image']) != ''){
			$upload_dir = wp_upload_dir();

			$image_data = file_get_contents($my_post['image']);
			$filename = basename($my_post['image']);
			@unlink($my_post['image']);
			if(wp_mkdir_p($upload_dir['path']))
			    $file = $upload_dir['path'] . '/' . $filename;
			else
			    $file = $upload_dir['basedir'] . '/' . $filename;
			file_put_contents($file, $image_data);

			if(filesize($file) < 1624 && !$byPassImage){
				return null;
			}

			$wp_filetype = wp_check_filetype($filename, null );
			$attachment = array(
			    'post_mime_type' => $wp_filetype['type'],
			    'post_title' => sanitize_file_name($filename),
			    'post_content' => '',
			    'post_status' => 'inherit'
			);
		}
		if($byPassImage && trim($my_post['image']) == ''){
			$my_post['post_status'] = 'pending';
		}
		$my_post['filter'] = true;
		// Post filtering
		remove_filter('content_save_pre', 'wp_filter_post_kses');
		remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');

		$post_id = wp_insert_post($my_post);

		// Post filtering
		add_filter('content_save_pre', 'wp_filter_post_kses');
		add_filter('content_filtered_save_pre', 'wp_filter_post_kses');

		if($file){
			$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
			$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
			wp_update_attachment_metadata( $attach_id, $attach_data );

			set_post_thumbnail( $post_id, $attach_id );
		}
		return $post_id;
	}
	catch(Exception $e){
		return $e->getMessage();
	}
}

function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }  
    return strpos($content,$str) ? true : false;
}
function getFirstImg($content)
{
    $img = "";
  preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $matches);
  $urlimage = $matches[1];
    foreach($urlimage as $img)
    {
        if(contains("jpg", $img) || contains("gif", $img) || contains("png", $img))
        {
            return $img;
            break;
        }
    }
    if($img == '')
    {
        return "";
    }
}
